package com.kusiri.kframework.salesforce.model.valueobjectlist
{
	import com.kusiri.kframework.model.IKfValueObject;
	import com.kusiri.kframework.salesforce.model.ISObject;
	import com.kusiri.kframework.salesforce.model.KfSalesforceModel;
	import com.kusiri.kframework.salesforce.model.SObject;
	import com.kusiri.kframework.ui.*;
	
	import mx.collections.ArrayCollection;
	
	public class MyTasksValueObjectList extends SObjectList implements IMyTasksValueObjectList
	{
		private var self:MyTasksValueObjectList;

		private var _ownerId : String;

		public function MyTasksValueObjectList() : void
		{
			self = this;
			_type = 'Task';
		}


		/**
		 * Get the value objects
		 */
		override public function refetchValueObjects(onSuccess : Function = null, onFail : Function = null) : void
		{
			var sfModel : KfSalesforceModel = model as KfSalesforceModel;
			_ownerId = sfModel.__currentUserId;
			sfModel.getSObjects('Task', "WHERE OwnerId='"+_ownerId+"' ORDER BY ActivityDate ASC",
			function (result:ArrayCollection) : void
			{
				_valueObjects = result.source;
				if (onSuccess != null) onSuccess(self);
			},
			function (e:*) : void
			{
				if (onFail != null) onFail(e);
			});
		}
		
		/**
		 * Whether or not the value Object belongs in this list
		 */
		override protected function valueObjectBelongs( valueObject : IKfValueObject ) : Boolean
		{
			if ( ! (valueObject is ISObject) ) return false;
			var sobject : ISObject = valueObject as ISObject;
			if (sobject.__type != 'Task' || (sobject as Object).OwnerId != _ownerId) return false;
			return true;
		}
		
		/**
		 * Insert a value object, and return the place at which it is entered
		 */
		override protected function getValueObjectPosition( valueObject : IKfValueObject ) : int
		{
			var pos : int = 0;
			var date : Date = (valueObject as SObject).ActivityDate;
			if ( date != null )
			{
				for each (var vo : SObject in valueObjects)
				{
					if ( vo.ActivityDate == null ) continue;
					if ( date < vo.ActivityDate ) break;
					pos++;
				} 
			}
			return pos;
		}
		
	}
}